package cn.hua.trip.app.base.controller;

import cn.hua.trip.app.base.util.UserContext;
import cn.hua.trip.base.domain.Region;
import cn.hua.trip.base.domain.Travel;
import cn.hua.trip.base.domain.User;
import cn.hua.trip.base.query.TravelQueryObject;
import cn.hua.trip.base.service.ITravelService;
import cn.hua.trip.base.service.IUserService;
import cn.hua.trip.base.util.JSONResult;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/users")
public class UserController {
    /*
    * 注册功能设计
    *
    * 资源:users
    * 访问方式:POST
    * 请求参数:email,password
    * 返回结果:json
    * */

    @Autowired
    private IUserService userService;
    @Autowired
    private ITravelService travelService;

    @PostMapping
    public Object regist(User user){
        JSONResult result = new JSONResult();
        //1.去数据库中查询是否存在同样的email,有就不能注册,弹出框告诉用户
       try {
           userService.regist(user);


       }catch (Exception e){
            result.mark(e.getMessage());
       }
        //2.如果没有相同的邮箱就注册成功,告诉用户可以登录
        return result;
    }


    @PutMapping
    public Object updateUser(User user){
        JSONResult result = new JSONResult();
        //1.如果没抛异常就是更新成功数据库的内容
        try {

            userService.update(user);
            //返回最新的数据给页面
            User user1 = userService.get(user.getId());
            result.setData(user1);
            UserContext.setCurrentUser(user1);
        }catch (Exception e){
            result.mark(e.getMessage());
        }
        //2.返回一个结果给回调函数
        return result;
    }


    @GetMapping("/{userId}/travels")
    public Object getTravel(TravelQueryObject qo){
        PageInfo<Travel> pageInfo = travelService.queryForList(qo);
        return pageInfo;
    }
}
